package com.abiao.shop.config;

import com.abiao.shop.pojo.User;
import com.abiao.shop.service.UserService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: UserArgumentResolver
 * 用户参数解析器，实现Cookie转化为用户实体
 * @Author: AB
 * @Date: 2021-07-16
 * @Version:v1.0
 */
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    UserService userService;

    @Override   //判断参数类型为User再进行下一步处理
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> clazz = parameter.getParameterType();  //利用反射，获取形参类型，返回class
        return clazz == User.class;
    }

    @Override   //自定义参数解析（解析cookie生成User实体返回给controller）
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);

        assert request != null;
        //移动端有时会吧cookie放入参数中传入
        String parameterToken = request.getParameter(UserService.COOKIE_NAME_TOKEN);
        //获取cookie的token
        String cookieToken = getCookieValue(request);
        if (StringUtil.isNullOrEmpty(cookieToken)&&StringUtil.isNullOrEmpty(parameterToken)){
            return null;
        }
        String token = parameterToken==null?cookieToken:parameterToken;
        User user = userService.getByToken(response,token);
        return user;
    }

    //从request中获取指定cookie（UserService.COOKIE_NAME_TOKEN）
    private String getCookieValue(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null||cookies.length<=0){
            return null;
        }
        for (Cookie cookie:cookies){
            if (cookie.getName().equals(UserService.COOKIE_NAME_TOKEN)){
                return cookie.getValue();
            }
        }
        return null;
    }

}
